package jsyf.oa.service.report.attendance;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.report.attendance.AttendanceDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.facade.report.attendance.AttendanceFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2018/4/7 0007.
 */
@Service
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class AttendanceService implements AttendanceFacade {

    @Autowired
    private AttendanceDao attendanceDao;
    @Autowired
    private UserDao userDao;

    @Override
    public JSONObject getSignPersonByToday(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String nowTime = "";
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            nowTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        } else {
            nowTime = dateTime;
        }
        //获取个人考勤信息,判断出勤、缺勤、请假
        JSONObject signToday = attendanceDao.getSignPersonByToday(userId, nowTime);
        JSONObject leaveToday = attendanceDao.getLeavePersonByToday(userId, nowTime);
        if (signToday != null) {
            if ("1".equals(signToday.getString("frontFlag"))) {
                if ("08:00".compareTo(signToday.getString("signCreateTime")) < 0) {
                    signToday.put("remind", "1");
                }
            } else {
                if ("08:30".compareTo(signToday.getString("signCreateTime")) < 0) {
                    signToday.put("remind", "1");
                }
            }
            return signToday;
        } else if (leaveToday != null) {
            return leaveToday;
        } else {
            JSONObject result = new JSONObject();
            result.put("signState", "2");
            result.put("remind", "1");
            return result;
        }
    }

    @Override
    public List<JSONObject> getForPersonalByUserIdAndDateTime(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        if (dateTime.length() == 10) {
            return attendanceDao.getSignPersonByUserIdAndDateTime(userId, dateTime);
        } else {
            //获取某月考勤信息
            List<JSONObject> list = attendanceDao.getViewJSONListByCondition(" AND userId = ? AND LEFT(signDate,7) = ? ORDER BY signDate DESC",
                    new Object[]{userId, dateTime});
            //返回的集合
            List<JSONObject> dayList = new ArrayList<>();
            //已过去的天数
            List<String> arrayDayList = new ArrayList<>();
            //当前日期
            Calendar c = Calendar.getInstance();
            String month = DateUtils.parse(c.getTime(), "yyyy-MM");
            if (dateTime.equals(month)) {
                //当月，获取当天是本月的第几天
                Integer days = c.get(Calendar.DAY_OF_MONTH);
                for (Integer i = days; i >= 1; i--) {
                    arrayDayList.add(dateTime + "-" + (i < 10 ? ("0" + i) : i));
                }
            } else {
                //非当月，获取某月最后一天
                Integer lastDay = DateUtils.getLastDayOfMonth(Integer.valueOf(dateTime.split("-")[0]),
                        Integer.valueOf(dateTime.split("-")[1]));
                for (Integer i = lastDay; i >= 1; i--) {
                    arrayDayList.add(dateTime + "-" + (i < 10 ? ("0" + i) : i));
                }
            }
            for (int i = 0; i < arrayDayList.size(); i++) {
                String day = arrayDayList.get(i);
                JSONObject objResult = new JSONObject();
                objResult.put("id", "");
                objResult.put("signDate", arrayDayList.get(i));
                objResult.put("userId", userId);
                objResult.put("signState", "2");
                for (Integer j = 0; j < list.size(); j++) {
                    if (day.equals(list.get(j).get("signDate"))) {
                        objResult.put("id", list.get(j).get("id"));
                        objResult.put("userId", list.get(j).get("userId"));
                        objResult.put("startAddress", list.get(j).get("startAddress"));
                        objResult.put("signUrl", list.get(j).get("signUrl"));
                        objResult.put("signCreateTime", DateUtils.parse((Date) list.get(j).get("signCreateTime"), "HH:mm"));
                        if (!StringUtils.isBlank(list.get(j).get("signOutTime").toString())) {
                            objResult.put("signOutTime", DateUtils.parse((Date) list.get(j).get("signOutTime"), "HH:mm"));
                            objResult.put("endAddress", list.get(j).get("endAddress"));
                            objResult.put("signOutUrl", list.get(j).get("signOutUrl"));
                        }
                        objResult.put("signState", list.get(j).get("signState"));

                    }
                }
                dayList.add(objResult);
            }
            return dayList;
        }
    }

    @Override
    public JSONObject getSignInByUserId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String frontFlag = jsonParams.getString("frontFlag");
        JSONObject users = userDao.getJSONById(userId);
        String entryDate = users.getString("entryDate");
        //当前日期
        Calendar c = Calendar.getInstance();
        String nowTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        String firstTime = DateUtils.getFirstDayOfMonth();
        JSONObject result = attendanceDao.getSignInByUserId(userId, dateTime,
                Integer.valueOf(frontFlag), nowTime, firstTime, entryDate);
        Integer todayCount = Integer.valueOf(result.get("todayCount").toString());
        Integer signInCount = Integer.valueOf(result.get("signInCount").toString());
        Integer leaveCount = Integer.valueOf(result.get("leaveCount").toString());
        Integer absenceCount = todayCount - signInCount - leaveCount;
        result.put("entryDate", entryDate.substring(0, 10));
        result.put("absenceCount", absenceCount < 0 ? 0 : absenceCount);
        return result;
    }

    @Override
    public JSONObject getSignInByRegionUserId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String departId = jsonParams.getString("departId");
        String dateTime = jsonParams.getString("dateTime");
        //当前日期
        Calendar c = Calendar.getInstance();
        String nowTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        JSONObject result = attendanceDao.getSignInByRegionUserId(dateTime, userId, departId, nowTime);
        Integer todayCount = Integer.valueOf(result.get("shouldCount").toString());
        Integer signInCount = Integer.valueOf(result.get("signInCount").toString());
        Integer leaveCount = Integer.valueOf(result.get("leaveCount").toString());
        Integer absenceCount = todayCount - signInCount - leaveCount;
        result.put("absenceCount", absenceCount < 0 ? 0 : absenceCount);
        return result;
    }

    @Override
    public List<JSONObject> getForDepartByUserIdAndDateTime(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String front = jsonParams.getString("frontFlag");
        String departId = jsonParams.getString("departId");
        String dateTime = jsonParams.getString("dateTime");
        String frontFlag = "";
        if (StringUtils.isBlank(front)) {
            if (!StringUtils.isBlank(userId)) {
                JSONObject obj = userDao.getViewJSONById(userId);
                frontFlag = obj.getString("frontFlag");
            }
        } else {
            frontFlag = front;
        }
        List<JSONObject> resluts = new ArrayList<>();
        if (dateTime.length() == 10) {
            resluts = attendanceDao.getRegionBySignInList(userId, dateTime, departId, frontFlag);
        } else {
            //当前日期
            Calendar c = Calendar.getInstance();
            String nowTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
            String firstTime = DateUtils.getFirstDayOfMonth();
            String dayTime = DateUtils.parse(c.getTime(), "dd");
            String monthTime = DateUtils.parse(c.getTime(), "yyyy-MM");

            resluts = attendanceDao.getRegionByMonthList(userId, dateTime, departId, nowTime, firstTime, dayTime, monthTime, frontFlag);
        }
        return resluts;
    }

    @Override
    public List<JSONObject> getForCompanyByUserIdAndDateTime(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String companyId = jsonParams.getString("companyId");
        String dateTime = jsonParams.getString("dateTime");
        List<JSONObject> results = new ArrayList<>();
        if (dateTime.length() == 10) {
            results = attendanceDao.getCompanyByTodayList(userId, dateTime, companyId);
        } else {
            //当前日期
            Calendar c = Calendar.getInstance();
            String nowTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
            String firstTime = DateUtils.getFirstDayOfMonth();
            String dayTime = DateUtils.parse(c.getTime(), "dd");
            String monthTime = DateUtils.parse(c.getTime(), "yyyy-MM");
            results = attendanceDao.getCompanyByMonthList(userId, dateTime, companyId, nowTime, firstTime, dayTime, monthTime);
        }
        return results;
    }

    @Override
    public List<JSONObject> getForGroupByUserIdAndDateTime(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        StringBuilder sbMonthdays = new StringBuilder();
        List<JSONObject> results = new ArrayList<>();
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" and id = ? ", new Object[]{userId});
        for (int i = 0; i < userList.size(); i++) {
            String companyId = userList.get(i).getString("companyId");
            if (i == 0) {
                sbMonthdays.append(" AND (ID = '" + companyId + "' OR PARENT_ID = '" + companyId + "' AND DEL_FLAG=0) ");
            } else {
                sbMonthdays.append(" OR (ID = '" + companyId + "' OR PARENT_ID = '" + companyId + "' AND DEL_FLAG=0) ");
            }
        }
        if (dateTime.length() == 10) {
            results = attendanceDao.getGroupByTodayList(dateTime, sbMonthdays.toString());
        } else {
            //当前日期
            Calendar c = Calendar.getInstance();
            String nowTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
            List<JSONObject> signList = attendanceDao.getGroupByMonthList(dateTime, sbMonthdays.toString(), nowTime);
            return signList;
        }
        return results;
    }

    @Override
    public List<JSONObject> getForSignInByTypeAndDateTime(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String companyId = jsonParams.getString("companyId");
        String departId = jsonParams.getString("departId");
        String dateTime = jsonParams.getString("dateTime");
        String type = jsonParams.getString("type");
        List<JSONObject> results = new ArrayList<>();
        if (dateTime.length() == 10) {
            if ("1".equals(type)) {
                results = attendanceDao.getForSignInByTypeAndDateTime(dateTime, companyId, departId, "0");
            } else if ("2".equals(type)) {
                results = attendanceDao.getForSignInByTypeAndDateTime(dateTime, companyId, departId, "1");
            } else {
                results = attendanceDao.getForSignInByTypeAndDateTime(dateTime, companyId, departId, "");
            }
        } else {
            Calendar c = Calendar.getInstance();
            String nowTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
            if ("1".equals(type)) {
                results = attendanceDao.getForSignInByTypeAndMonthTime(dateTime, companyId, departId, "0", nowTime);
            } else if ("2".equals(type)) {
                results = attendanceDao.getForSignInByTypeAndMonthTime(dateTime, companyId, departId, "1");
            } else {
                results = attendanceDao.getForSignInByTypeAndMonthTime(dateTime, companyId, departId, "");
            }
        }
        return results;
    }

    @Override
    public List<JSONObject> getShouldExcel(String dateTime, String companyId) {

        List<JSONObject> signInList = attendanceDao.getSignExcel(dateTime, companyId);
        return signInList;
    }

    @Override
    public List<JSONObject> getWrtReportExcel(String userId, String dateTime) {
        return attendanceDao.getWrtReportExcel(userId, dateTime);
    }

    @Override
    public List<JSONObject> getShouldByUserIdAndDateTime(String userId, String dateTime) {
        List<JSONObject> signInList = attendanceDao.getLeaveAndAbsenceExcel(userId, dateTime);
        return signInList;
    }

    @Override
    public String getBackGround(String dateTime) {
        List<JSONObject> signInList = attendanceDao.getBackGround(dateTime);
        String signs = "";
        for (int k = 0; k < signInList.size(); k++) {
            signs += signInList.get(k).getString("shouldDate") + ",";
        }
        return signs;
    }

    @Override
    public List<JSONObject> getForManagerInByTypeAndMonthTime(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String type = jsonParams.getString("type");
        List<JSONObject> results = new ArrayList<>();
        if ("1".equals(type)) {
            results = attendanceDao.getForManagerInByTypeAndMonthTime(dateTime, userId, "0");
        } else if ("2".equals(type)) {
            results = attendanceDao.getForManagerInByTypeAndMonthTime(dateTime, userId, "1");
        } else {
            results = attendanceDao.getForManagerInByTypeAndMonthTime(dateTime, userId, "");
        }
        return results;
    }

    @Override
    public Integer getRealRest(String dateTime, String userId) {
        Calendar c = Calendar.getInstance();
        String nowTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        return attendanceDao.getRealRest(dateTime, userId, nowTime);
    }

    @Override
    public Integer getLeaveRest(String dateTime, String userId, String frontFlag) {
        return attendanceDao.getLeaveRest(dateTime, userId, frontFlag);
    }

    @Override
    public Integer getSignRest(String dateTime, String userId, String frontFlag) {
        return attendanceDao.getSignRest(dateTime, userId, frontFlag);
    }

    @Override
    public Integer getOverTime(String dateTime, String userId, String frontFlag) {
        return attendanceDao.getOverTime(dateTime, userId, frontFlag);
    }


}
